import React, { useState } from 'react';
import {
    Input,
    Button,
    Checkbox,
    Toast,
    Image
} from 'antd-mobile';
import {
    HeartOutline,
    PictureOutline,
    CameraOutline,
    AddOutline,
    TruckOutline
} from 'antd-mobile-icons';
import styles from './index.module.css';
import { 
    TEST_ACCOUNTS,
    mockLoginSuccess, 
    validateCredentials 
} from '../../data/auth';
import { 
    generateGiteeAuthUrl 
} from '../../data/gitee';

const Index: React.FC = () => {
    const [activeTab, setActiveTab] = useState('verification');
    const [phone, setPhone] = useState('');
    const [verificationCode, setVerificationCode] = useState('');
    const [password, setPassword] = useState('');
    const [countdown, setCountdown] = useState(0);
    const [agreed, setAgreed] = useState(false);
    const [isLoading, setIsLoading] = useState(false);



    // 获取验证码
    const handleGetCode = () => {
        if (!phone || phone.length !== 11) {
            Toast.show('请输入正确的手机号码');
            return;
        }

        if (countdown > 0) return;

        setCountdown(60);
        const timer = setInterval(() => {
            setCountdown((prev) => {
                if (prev <= 1) {
                    clearInterval(timer);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);

        Toast.show('验证码已发送');
    };

    // 登录处理
    const handleLogin = async () => {
        if (!agreed) {
            Toast.show('请先同意相关协议');
            return;
        }

        if (activeTab === 'verification') {
            if (!phone || !verificationCode) {
                Toast.show('请填写完整信息');
                return;
            }

            // 验证码登录逻辑
            const validation = validateCredentials(phone, '', verificationCode);
            if (validation.success) {
                await handleLoginSuccess();
            } else {
                Toast.show('验证码错误');
            }
        } else {
            if (!phone || !password) {
                Toast.show('请填写完整信息');
                return;
            }

            // 密码登录逻辑
            const validation = validateCredentials(phone, password);
            if (validation.success) {
                await handleLoginSuccess();
            } else {
                Toast.show('手机号或密码错误');
            }
        }
    };

    // 处理登录成功
    const handleLoginSuccess = async () => {
        setIsLoading(true);

        try {
            // 使用 mock 数据
            const userData = await mockLoginSuccess();

            // 存储到 localStorage
            localStorage.setItem('userToken', userData.token);
            localStorage.setItem('userData', JSON.stringify(userData.user));

            Toast.show({
                content: `欢迎回来，${userData.user.name}！`,
                duration: 2000,
                afterClose: () => {
                    // 这里可以跳转到主页面
                    console.log('登录成功，用户数据：', userData);
                    // 例如：navigate('/home') 或 window.location.href = '/home'
                    window.location.href = '/home';
                }
            });

        } catch {
            Toast.show('登录失败，请重试');
        } finally {
            setIsLoading(false);
        }
    };

    // 码云登录
    const handleGiteeLogin = () => {
        // 使用 mock 数据中的配置
        const { url, state } = generateGiteeAuthUrl();

        // 存储 state 到 localStorage，用于验证回调
        localStorage.setItem('gitee_state', state);

        // 重定向用户到码云授权页面
        window.location.href = url;
    };

    return (
        <div className={styles['login-container']}>
            {/* 背景装饰图标 */}
            <div className={styles['background-icons']}>
                <PictureOutline className={`${styles['bg-icon']} ${styles.cloud}`} />
                <CameraOutline className={`${styles['bg-icon']} ${styles.camera}`} />
                <AddOutline className={`${styles['bg-icon']} ${styles.plus}`} />
                <TruckOutline className={`${styles['bg-icon']} ${styles.truck}`} />
            </div>

            {/* 主要内容 */}
            <div className={styles['main-content']}>
                {/* 标题区域 */}
                <div className={styles['title-section']}>
                    <h1 className={styles['main-title']}>智慧医院便民平台</h1>
                    <p className={styles.subtitle}>开启智慧医疗新时代</p>
                </div>

                {/* 登录方式切换 */}
                <div className={styles['login-tabs']}>
                    <div
                        className={`${styles.tab} ${activeTab === 'verification' ? styles.active : ''}`}
                        onClick={() => setActiveTab('verification')}
                    >
                        验证码登录
                    </div>
                    <div className={styles['tab-divider']}></div>
                    <div
                        className={`${styles.tab} ${activeTab === 'password' ? styles.active : ''}`}
                        onClick={() => setActiveTab('password')}
                    >
                        密码登录
                    </div>
                </div>

                {/* 登录表单 */}
                <div className={styles['login-form']}>
                    {/* 手机号输入 */}
                    <div className={styles['input-group']}>
                        <Input
                            className={styles['phone-input']}
                            placeholder="请输入您的手机号码"
                            value={phone}
                            onChange={setPhone}
                            maxLength={11}
                            type="tel"
                        />
                    </div>

                    {/* 验证码/密码输入 */}
                    <div className={styles['input-group']}>
                        {activeTab === 'verification' ? (
                            <div className={styles['verification-group']}>
                                <Input
                                    className={styles['verification-input']}
                                    placeholder="请输入手机验证码"
                                    value={verificationCode}
                                    onChange={setVerificationCode}
                                    maxLength={6}
                                    type="number"
                                />
                                <Button
                                    className={styles['get-code-btn']}
                                    fill="none"
                                    disabled={countdown > 0}
                                    onClick={handleGetCode}
                                >
                                    {countdown > 0 ? `${countdown}s` : '获取验证码'}
                                </Button>
                            </div>
                        ) : (
                            <Input
                                className={styles['password-input']}
                                placeholder="请输入密码"
                                value={password}
                                onChange={setPassword}
                                type="password"
                            />
                        )}
                    </div>

                    {/* 验证码登录提示 */}
                    {activeTab === 'verification' && (
                        <p className={styles['verification-hint']}>
                            验证码登录可一键注册或登录
                        </p>
                    )}

                    {/* 登录按钮 */}
                    <Button
                        className={styles['login-btn']}
                        block
                        color="primary"
                        size="large"
                        loading={isLoading}
                        disabled={isLoading}
                        onClick={handleLogin}
                    >
                        {isLoading ? '登录中...' : '登录'}
                    </Button>

                    {/* 微信登录 */}
                    <div className={styles['wechat-login']} onClick={handleGiteeLogin}>
                        <Image src='https://ts1.tc.mm.bing.net/th/id/OIP-C.AMXmzrHF8yVgJkfe00eIxAAAAA?r=0&rs=1&pid=ImgDetMain&o=7&rm=3' className={styles['wechat-icon']}></Image>
                        {/* <HeartOutline className={styles['wechat-icon']} /> */}
                        <span>码云一键登录</span>
                    </div>
                </div>

                {/* 协议同意 */}
                <div className={styles['agreement-section']}>
                    <Checkbox
                        checked={agreed}
                        onChange={setAgreed}
                        className={styles['agreement-checkbox']}
                    />
                    <span className={styles['agreement-text']}>
                        我已阅读并同意
                        <a href="#" className={styles['agreement-link']}>隐私政策</a>
                        和
                        <a href="#" className={styles['agreement-link']}>用户协议</a>
                        和
                        <a href="#" className={styles['agreement-link']}>平台协议</a>
                    </span>
                </div>

                        {/* 测试账号提示 */}
        <div className={styles['test-account']}>
            <p>测试账号：手机号 {TEST_ACCOUNTS.PHONE}，密码 {TEST_ACCOUNTS.PASSWORD}</p>
        </div>
            </div>
        </div>
    );
};

export default Index;
